import Vue from 'vue'
import axios from 'axios';
import baseUrl from "./apiConfig";
import {Message, MessageBox, Loading} from 'element-ui';
import {getStore} from "../utils/tools";
import router from '../../router/index';

Vue.component(MessageBox.name, MessageBox, Message, Loading);

let loadingInstance = null;
let num = 0;
let startLoading = () => {
  loadingInstance = Loading.service({
    lock: true,
    text: '拼命加载中',
    spinner: 'el-icon-loading',
    // background: 'rgba(0, 0, 0, 0.8)'
  });
}

// 添加请求拦截器
axios.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  num++;
  startLoading();
  return config;
}, error => {
  // 对请求错误做些什么
  loadingInstance.close();
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(response => {
  // 对响应数据做点什么
  num--;
  if (num <= 0) {
    loadingInstance.close();
  }
  return response;
}, error => {
  // 对响应错误做点什么
  loadingInstance.close();
  return Promise.reject(error);
});

const getUrl = (url) => {
  let apiConfig = {
    "development": baseUrl.dev,
    "test": baseUrl.test,
    "production": baseUrl.prod,
  };
  return apiConfig[process.env.NODE_ENV] + url
};

const $http = (type, url, data, dataType = 'json') => {
  const timeout = 20000;
  let contentType = null;
  let formData = new FormData();
  /** 对参数进行的处理 */
  if (dataType == 'formData') {
    for (let key in data) {
      formData.append(key, data[key])
    }
    contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
  } else {
    if (type == 'get') {
      // url = url + "?" + qs.stringify(data);
      contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
    } else {
      data = JSON.stringify(data);
      contentType = 'application/json; charset=UTF-8';
    }
  }
  /** 处理完请求方法和参数以后 通过axios进行请求 */
  let promise = new Promise((resove, reject) => {
    let config = {
      method: type,
      url: getUrl(url),
      // data: dataType == "formData" ? formData : data,
      timeout: timeout,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': contentType,
        'token': getStore("token")
      }
    };
    if (type == "get") {
      Object.assign(config, {params: data})
    } else {
      Object.assign(config, {data: dataType == "formData" ? formData : data})
    }
    return axios(config)
      .then(function (resp) {
        let json = resp.data;
        if (json.code == 0) {
          resove(json);
        } else if (json.code == 5) {
          Message.error('登陆过期!');
          router.push({path: "/login"});
        } else {
          Message.error(json.msg || json.message);
          reject(json);
        }
      }).catch(function (err) {
        if (err.response && err.response.data) {
          Message.error(err.response.data.error);
          reject(err.response.data.error);
        } else {
          Message.error('请求超时!');
        }
      })
  });
  return promise;
};

export default $http;
